extends NodeState

@export var zombie: Zombie

var attack_timer: float    = 0.0
var attack_duration: float = 0.5  # 攻击动画持续时间


func _on_enter() -> void:
	if zombie and not zombie.is_dead:
		# 停止移动
		zombie.velocity = Vector2.ZERO
		# 执行攻击
		zombie.perform_attack()
		attack_timer = 0.0


func _on_physics_process(delta: float) -> void:
	attack_timer += delta

	# 攻击过程中面向玩家
	if zombie and zombie.target_player and not zombie.is_dead:
		var direction: Vector2 = zombie.get_direction_to_player()
		if direction.x < 0:
			zombie.animated_sprite.flip_h = true
		elif direction.x > 0:
			zombie.animated_sprite.flip_h = false


func _on_next_transitions() -> void:
	if not zombie or zombie.is_dead:
		if zombie and zombie.is_dead:
			transition.emit("die")
		return
	
	if not zombie.target_player:
		transition.emit("idle")
		return

	# 攻击动画结束后检查状态转换
	if attack_timer >= attack_duration:
		zombie.is_attacking = false

		var distance: float = zombie.get_distance_to_player()

		# 如果玩家仍在攻击范围内且可以攻击，继续攻击
		if distance <= zombie.attack_range and zombie.can_attack():
			# 重新进入攻击状态
			attack_timer = 0.0
			zombie.perform_attack()
			# 如果玩家在检测范围内但不在攻击范围内，追击
		elif distance <= zombie.detection_range:
			transition.emit("walk")
		# 如果玩家超出检测范围，回到空闲状态
		else:
			transition.emit("idle")


func _on_exit() -> void:
	if zombie:
		zombie.is_attacking = false
